const toFixed2 = (num) => {
  return !isNaN(Number(num)) ? Number(Number(num).toFixed(2)) : 0
}
/**
 * @description 计算账单数据
 * @property {array} cartList -购物车列表 amount-加购数量 
 * @property {object} vipInfo -会员信息 member_level_no,menber_no
 * @property {object} discountData -折扣数据
 * @property {object} couponInfo -优惠券信息 需要这三个字段 member_coupon_no,use_threshold,coupon_discount
 * @property {array} vipPriceList -会员价列表  srvretail_goods_member_select
 * @property {array} activityList - 营销活动列表 srvmkt_available_promotion_activity_select
 * @property {object} vipSetting - 会员优惠设置 srvretail_member_setup_select
 * @property {object} otherData - 计算无关参数 
 */
const calcBillResult = (cartList = [], vipInfo = null, discountData = {
  type: "", // inCart,vip|discount|change|free|coupon|promotion 购物车状态，会员价、整单折扣、整单改价、免单、优惠券、促销活动
  promotionInfo: null, //选择的促销活动
  discountAmount: 0, // 整单减免金额/整单折扣比例（0-100）
  subtractPrice: 0, //抹零金额
  vipPayAmount: 0, //会员余额支付金额
  integralPayAmount: 0, //积分抵扣金额
}, couponInfo = {
  member_coupon_no: "", // 会员优惠券编号
  use_threshold: "", // 使用门槛 无门槛|最低消费
  coupon_discount: 0 //优惠券减免金额
}, vipPriceList = null, activityList = null, vipSetting = null, otherData = {
  pay_type: "",
  discount_reason: "",
  discount_reason_name: "",
  remark: "",
  store_no: "",
  order_channel: "",
  sales_clerk: "",
  sales_clerk_staff: "",
}) => {
  try {
    if (typeof cartList === 'string') {
      cartList = JSON.parse(cartList)
    }
  } catch (e) {}
  try {
    if (typeof vipInfo === 'string') {
      vipInfo = JSON.parse(vipInfo)
    }
  } catch (e) {}
  try {
    if (typeof discountData === 'string') {
      discountData = JSON.parse(discountData)
    }
  } catch (e) {}
  try {
    if (typeof couponInfo === 'string') {
      couponInfo = JSON.parse(couponInfo)
    }
  } catch (e) {}
  try {
    if (typeof vipPriceList === 'string') {
      vipPriceList = JSON.parse(vipPriceList)
    }
  } catch (e) {}
  try {
    if (typeof activityList === 'string') {
      activityList = JSON.parse(activityList)
    }
  } catch (e) {}
  try {
    if (typeof vipSetting === 'string') {
      vipSetting = JSON.parse(vipSetting)
    }
  } catch (e) {}
  try {
    if (typeof otherData === 'string') {
      otherData = JSON.parse(otherData)
    }
  } catch (e) {}

  const member_level_no = vipInfo && vipInfo.member_level_no ? vipInfo.member_level_no : '';
  const member_no = vipInfo && vipInfo.member_no ? vipInfo.member_no : vipInfo && vipInfo.menber_no ? vipInfo
    .menber_no : ''

  const {
    member_coupon_no, // 会员优惠券编号
    use_threshold, // 使用门槛 无门槛|最低消费
    // discount_amount: coupon_discount //优惠券减免金额
  } = couponInfo || {}


  let discountType = discountData.type;


  const $vipSetting = vipSetting || {} //会员折扣设置
  const enable_member_discount = $vipSetting && $vipSetting.enable_member_discount ? $vipSetting
    .enable_member_discount : ''
  let $activityList = activityList || [] //活动列表
  // const cartGoodsNos = [...new Set(cartList.map(item => item.goods_no))]
  // if (!['discount', 'change'].includes(discountType)) {
  //   $activityList = $activityList.reduce((pre, cur) => {
  //     if (cartGoodsNos && cartGoodsNos.includes(cur.goods_no)) {
  //       if (cur && cur.participants === '指定会员等级') {
  //         if (!member_level_no || cur.member_level_name && member_level_no && cur.member_level_name.indexOf(
  //             member_level_no) === -1) {
  //           return pre
  //         }
  //       }

  //       if (cur && cur.weekly_take_effect) {
  //         let weekly = new Date().getDay() // 0-6
  //         let weekMap = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  //         if (cur.weekly_take_effect.indexOf(weekMap[weekly]) === -1) {
  //           return pre
  //         }
  //       }
  //       const activityIndex = pre.findIndex(item => item.promotion_no === cur.promotion_no)
  //       if (activityIndex !== -1) {
  //         pre[activityIndex]._goods_nos.push(cur.goods_no)
  //         pre[activityIndex]._goodsList.push({...cur})
  //       } else {
  //         cur._goods_nos = [cur.goods_no]
  //         cur._goodsList = [{...cur}]
  //         pre.push(cur)
  //       }
  //     }
  //     return pre
  //   }, [])
  // }



  const {
    discountAmount, // 整单减免金额/整单折扣比例（0-100）
    subtractPrice, //抹零金额
    vipPayAmount, //会员余额支付金额
    integralPayAmount, //积分抵扣金额
    useIntegral //使用的积分数量
  } = discountData

  if (discountType === 'vip' && !member_level_no) {
    discountType = ''
  }

  const result = {
    order_total_amount: 0, // 订单总金额，不使用优惠的
    order_amount: 0, //订单金额 折扣、优惠、抹零过后的金额
    channel_source: "", //订单来源

    discount_mode: '无', //  打折/优惠方式 enum('无','打折','减免')
    discount_type: '不优惠', // enum('不优惠','整单手动打折/改价','免单')

    change_price: 0, //整单改价金额

    member_discount: 0, //会员价优惠金额
    discount_reduction_amount: 0, //	折扣/减免金额
    free_discount_amount: 0, //免单优惠金额
    cash_reduction_amount: 0, //抹零金额

    discount_full_decrement: 0, // 促销-满额减现 折扣金额
    discount_direct: 0, //	促销-直接折扣 折扣金额

    integral_deduction: 0, //积分抵扣金额

    coupon_discount: 0, // 优惠券优惠--金额
    coupon_no: '', // 优惠券编号

    discount_amount: 0, // 总优惠金额

    order_detail: [], // 订单商品详情

    _activities: [], // 参加的所有营销活动,

    // 不参与计算的信息
    member_no, //会员编号
    _order_total_amount_without_change_price: 0, //非改价商品价格合计
    _promotionList: [], //可参与的所有促销活动
  }
  result._promotionList = calcUsablePromotions(cartList, JSON.parse(JSON.stringify($activityList)), member_level_no)
  if (discountData && discountData.promotionInfo) {
    discountData.type = 'promotion'
    result.discount_full_decrement = discountData.promotionInfo._discount_full_decrement
    result.discount_direct = discountData.promotionInfo._discount_direct
    result.discount_amount = discountData.promotionInfo._discount_total_amount
  }
  if (Array.isArray(cartList) && cartList.length > 0) {
    cartList.forEach(item => {
      const amount = Number(item.amount || item.goods_num)
      item.amount = amount
      result.order_total_amount += amount * item.sale_price
      if (item.goods_price && item.goods_price !== item.sale_price) {
        return
      }
      result._order_total_amount_without_change_price += amount * item.sale_price
    })
    // result.order_total_amount = result.order_amount
  }
  // 优惠券
  if (!['discount', 'change', 'vip', 'promotion'].includes(discountType) && couponInfo && couponInfo
    .member_coupon_no) {
    // const curTime = new Date().getTime()
    // const startTime = new Date(couponInfo.available_start_time).getTime()
    // const endTime = new Date(couponInfo.available_end_time).getTime()
    // console.log(startTime,'startTime',couponInfo.available_start_time);
    // console.log(endTime,'endTime',couponInfo.available_end_time);
    // console.log(curTime,'curTime',new Date().getDate(),new Date().getHours(),new Date().getTime());
    // if (curTime < endTime && curTime > startTime) {
    // 在活动起止时间内
    if (use_threshold === '无门槛' || (use_threshold === "最低消费" && result.order_total_amount >=
        couponInfo.min_consumption)) {
      if (couponInfo.coupon_type === "折扣券") {
        // result.coupon_discount = toFixed2((couponInfo.discount_num * result.order_total_amount / 10) - result
        //   .order_total_amount)
        let discount = couponInfo.discount_num || 10
        discount = discount / 10
        if (discount > 1) {
          discount = 1
        }
        let coupon_discount = 0 //直接折扣减免的金额
        cartList.forEach(item => {
          item._coupon_discount = toFixed2(item.sale_price * item.amount * (1 - discount)) //折扣减免的金额
          item._cur_sale_price = (item.sale_price * item.amount + item._coupon_discount) / item.amount
          if (item._cur_sale_price < item.minimum_price && item.allow_min_sales_price === '不允许') {
            // 当前售价小于最低售价
            item._coupon_discount = (item.minimum_price - item.sale_price) * item.amount
            item._cur_sale_price = item.minimum_price
          }
          coupon_discount += item._coupon_discount
        })
        result.coupon_discount -= coupon_discount // 直接折扣
      } else {
        result.coupon_discount = couponInfo.discount_amount > result.order_total_amount ? -result
          .order_total_amount : -
          couponInfo.discount_amount
      }
      result.coupon_no = couponInfo.member_coupon_no
      result.discount_amount += result.coupon_discount
    }
    // }
  }


  // result._promotionList = $activityList
  if (Array.isArray(cartList) && cartList.length > 0) {
    cartList = JSON.parse(JSON.stringify(cartList))
    cartList.forEach(item => {
      const amount = item.amount || item.goods_num || 0
      // result.order_total_amount += amount * item.sale_price
      const _sale_price = item._origin_price || item.sale_price
      const obj = {
        goods_name: item.goods_name,
        "goods_no": item.goods_no,
        "goods_type": item.goods_type,
        "goods_barcode": item.goods_barcode,
        "goods_num": item.goods_num || item.amount || 0,
        "amount": item.amount || 0,
        "sale_price": item.sale_price,
        "subtotal_amount": 0, //小计金额
        "discount_amount": 0, //优惠金额
        "ctual_amount": 0, //实收金额
        "_new_sale_price": item._new_sale_price || item.sale_price,
        goods_stock: item.goods_stock,
        _vip_sub_amount: 0,
        // _activite_info: item._activite_info,
        _sale_price: _sale_price,
        _is_change_price: item._is_change_price || item.goods_price && item.goods_price !== item.sale_price,
        _discount_type: null,
        _change_price_discount: 0, //改价减的金额
        _buy_full_discount: 0, //满额减现
        _buy_discount: 0, // 直接折扣
        _discount_direct: item._discount_direct,
        _buy_discount_total: 0, //
        _buy_full_discount: 0,
        _buy_full_discount_total: 0,
        _integral_deduction: 0, //积分抵扣金额
        _activite: null,
        _activites: item._activites || [],
        _promotionList: item._promotionList || [],
        _originPrice: toFixed2(_sale_price * amount), // 原价小计
        _id: item._id
      }



      obj.subtotal_amount = amount * obj.sale_price
      obj.ctual_amount = amount * obj.sale_price
      if (obj._is_change_price === true) {
        // 改价的不参与任何促销
        obj._discount_type = '改'
        obj.discount_amount = toFixed2(amount * (obj._new_sale_price - _sale_price))
        obj._change_price_discount = obj.discount_amount
        // result.discount_amount += obj.discount_amount
        obj.ctual_amount += obj.discount_amount
        obj.subtotal_amount += obj.discount_amount
        // result.order_amount += obj.ctual_amount
        result.order_detail.push(obj)
        return
      }
      if (discountData && discountData.promotionInfo) {
        const promotionInfo = discountData.promotionInfo
        let promotGoods = promotionInfo._goodsList.find(e => e.goods_no === obj.goods_no)
        // result.order_amount += promotionInfo._discount_total_amount
        if (promotGoods && promotGoods.goods_no) {
          obj._buy_full_discount = promotGoods._buy_full_discount || 0
          obj._buy_discount = promotGoods._discount_direct || 0 //直接折扣
          if (obj._buy_discount) {
            obj.ctual_amount += obj._buy_discount
            obj.subtotal_amount += obj._buy_discount
            obj.discount_amount = obj._buy_discount
          } else if (obj._buy_full_discount) {
            obj.discount_amount = obj._buy_full_discount
            obj.ctual_amount += obj._buy_full_discount
            obj.subtotal_amount += obj._buy_full_discount
          }
        }
      }

      if (discountData && (!discountData.type || discountData.type == 'inCart') && obj._promotionList.length >
        0 && !result
        .coupon_no) {
        obj._discount_type = '促'
      } else if (discountData && discountData.type == 'promotion' && (obj._buy_full_discount || obj
        ._buy_discount) && !result
        .coupon_no) {
        obj._discount_type = '促'
      }

      let price = item.sale_price * amount
      obj._discount_type !== '促'
      if ((obj._discount_type !== '促') && vipInfo && vipInfo.discount_type !== '无' && item
        .allow_member_price == '允许' &&
        enable_member_discount === '是' && !
        member_coupon_no && (!
          discountType || discountType == 'vip' || discountType === 'inCart') && !obj
        ._buy_discount && !obj
        ._buy_full_discount) { // 使用会员价
        // 允许会员价 没有优惠券 非促销活动
        // 使用会员价 
        // vipPriceList
        let vipPrice = vipPriceList.find(e => e.goods_no == item.goods_no && e.member_level_no ===
          member_level_no);
        if (vipPrice && vipPrice.member_level_no && vipPrice.member_price_type !== '禁止') {
          if (vipInfo.discount_type && vipInfo.discount_type.indexOf('优惠价') > -1 && vipPrice
            .member_discount_amount && vipPrice.member_price_dis === '启用') {
            price = vipPrice.member_discount_amount * amount
          } else if (vipInfo.discount_type && vipInfo.discount_type.indexOf('打折') > -1 && vipPrice
            .discount_rate && vipPrice.discount_type && vipPrice.discount_type.indexOf('打折') > -
            1) {
            price = vipPrice.discount_rate * item.sale_price * amount / 100
          }
          // if (price !== item.sale_price * amount) {
            obj._vip_sub_amount = price - item.sale_price * amount
            obj.discount_amount += obj._vip_sub_amount
            result.member_discount += obj._vip_sub_amount
            result.discount_amount += obj._vip_sub_amount
            obj._discount_type = '会'
          // }
        }
        // result.order_amount += price
      } else if (discountType === 'discount') {
        // 整单手动打折
        // 整单手动折扣
        obj._finalPrice = Number(Number(obj.sale_price * Number(discountAmount) / 100).toFixed(
          2)) // 优惠价
        obj.subtotal_amount = obj._finalPrice * amount // 小计金额
        obj.ctual_amount = obj.subtotal_amount //实收金额
        obj._discount_sub_amount = obj.subtotal_amount - obj._originPrice
      } else if (discountType === 'free') {
        // 免单
        obj.subtotal_amount = 0
        obj.ctual_amount = 0
        obj.discount_amount = -obj._originPrice
      } else if (!result.coupon_no) {
        // result.order_amount += price
      }
      obj._id = item._id
      result.order_detail.push(obj)
    })

    if (result.discount_full_decrement) {
      // result.order_amount += result.discount_full_decrement // 促销-满额减现
    }

    if (result.discount_direct) {
      // result.order_amount += result.discount_direct //  促销-直接折扣
    }

    if (discountType === 'discount') {
      result.discount_mode = '打折'
      result.discount_type = '整单手动打折/改价'
      const order_amount = result.order_detail.reduce((pre, cur) => {
        pre += cur.subtotal_amount
        return pre
      }, 0)
      // result.order_amount = order_amount
      result.discount_reduction_amount = order_amount - result.order_total_amount
      result.discount_amount += result.discount_reduction_amount
      result.change_price = result.discount_reduction_amount
    } else if (discountType === 'change' && discountAmount) {
      // 整单手动减免
      // result.order_amount = result.order_total_amount - discountAmount
      result.discount_reduction_amount = -discountAmount
      result.discount_amount += result.discount_reduction_amount
      result.change_price = result.discount_reduction_amount

      // const rate = result.order_amount / result.order_total_amount
      result.order_detail = result.order_detail.map((cur, index) => {
        // if (cur._is_change_price == true) {
        //   return cur
        // }
        cur._change_sub_amount = -Number((discountAmount * cur._originPrice / result
          .order_total_amount).toFixed(
          2))
        // cur.subtotal_amount = Number(Number(cur.sale_price * cur.amount * rate).toFixed(2))
        // cur.discount_amount = cur.subtotal_amount - cur._originPrice
        // cur.ctual_amount = cur.subtotal_amount //实收金额
        return cur
      })

      result.discount_mode = '减免'
      result.discount_type = '整单手动打折/改价'

    } else if (discountType === 'free') {
      result.discount_type = '免单'
      result.order_amount = 0
      result._order_amount = 0
      result.discount_amount = -result.order_total_amount
      result.free_discount_amount = -result.order_total_amount
    }
    // 积分抵扣
    if (result.member_no && $vipSetting && $vipSetting.enable_member_integral === '是') {
      // 启用会员积分
      if ($vipSetting.integral_deduction === '启用') {
        // 启用积分抵扣
        // 每satisfy_deduction_integral,抵扣deduction_amount元
        if (integralPayAmount && !isNaN(Number(integralPayAmount))) {
          result.integral_deduction = toFixed2(-integralPayAmount)
          result.use_integral = toFixed2(integralPayAmount * $vipSetting.satisfy_deduction_integral)
          // result.order_amount += result.integral_deduction
          result.discount_amount += result.integral_deduction
          // result._order_amount = result.order_amount

          result.order_detail = result.order_detail.map(item => {
            item._integral_deduction = toFixed2(item.sale_price * item.amount * result.integral_deduction /
              result
              .order_total_amount)
            return item
          })
        } else if (useIntegral && !isNaN(Number(useIntegral))) {
          result.use_integral = useIntegral
          result.integral_deduction = toFixed2(-useIntegral / $vipSetting.satisfy_deduction_integral)
          result.discount_amount += result.integral_deduction
          result.order_detail = result.order_detail.map(item => {
            item._integral_deduction = toFixed2(item.sale_price * item.amount * result.integral_deduction /
              result
              .order_total_amount)
            return item
          })
        }
      }
    }

    // 抹零相关计算
    // result.order_amount = result.order_detail.reduce((res,cur)=>{
    //   return res+=cur.subtotal_amount
    // },0)
    result.order_amount = result.order_total_amount + result.discount_amount
    if (discountType !== 'free' && subtractPrice) {
      result.cash_reduction_amount = -subtractPrice
      result.discount_amount = result.order_amount - result.order_total_amount - subtractPrice
      result.order_amount = result.order_amount - subtractPrice
    }

    if (!isNaN(vipPayAmount) && vipPayAmount > 0) {
      result._vip_pay_order_amount = result.order_amount - vipPayAmount
      result._vip_pay_amount = vipPayAmount
    }

    let _coupon_discount = 0
    let other_discount_amount = 0
    const listLength = result.order_detail.length
    result.order_detail = result.order_detail.map((cur, index) => {
      // 将优惠金额按价格占比平均到每个商品
      cur.subtotal_amount = Number(Number(cur.sale_price * cur.amount).toFixed(2))
      // if (cur._buy_full_discount) {
      //   cur.subtotal_amount += cur._buy_full_discount
      // }
      // if (cur._buy_discount) {
      //   cur.subtotal_amount += cur._buy_discount
      // }

      cur._ml_sub_amount = -toFixed2((subtractPrice * cur._originPrice / result.order_total_amount))
      cur._free_sub_amount = result.free_discount_amount ? (result.free_discount_amount * cur
        ._originPrice / result
        .order_total_amount) : 0

      if (result.coupon_discount) {
        if (index > 0 && index === listLength - 1) {
          cur._coupon_discount = toFixed2(result.coupon_discount - _coupon_discount)
        } else {
          cur._coupon_discount = toFixed2(result.coupon_discount * cur._originPrice / result.order_total_amount)
          _coupon_discount += cur._coupon_discount
        }
      }

      cur.discount_amount = toFixed2(cur._buy_discount_total) + toFixed2(cur._buy_full_discount || 0) + toFixed2(
          cur._buy_full_discount_total) +
        toFixed2(
          cur._discount_sub_amount) + toFixed2(cur._change_sub_amount) + toFixed2(cur
          ._vip_sub_amount) + toFixed2(cur._ml_sub_amount) + toFixed2(cur._free_sub_amount) + toFixed2(cur
          ._integral_deduction) + toFixed2(cur._coupon_discount)
          
      if (cur.discount_amount + cur.subtotal_amount < 0) {
        cur.discount_amount = Math.abs(cur.subtotal_amount) * -1
      }
      
      cur.discount_amount = toFixed2(cur.discount_amount) //优惠价格

      cur.ctual_amount = toFixed2(cur.subtotal_amount + cur.discount_amount) //实收金额
      if (cur._free_sub_amount) {
        // 免单
        cur.subtotal_amount = 0
        cur.ctual_amount = 0
      }
      if (index !== listLength - 1) {
        other_discount_amount += toFixed2(cur.discount_amount)
      } else {
        cur.discount_amount = toFixed2(result.discount_amount - other_discount_amount)
      }
      return cur
    })

    result.order_amount = toFixed2(result.order_total_amount + result.discount_amount)
    result._order_amount = result.order_amount
    Object.keys(result).forEach(key => {
      if (result[key] && typeof result[key] === 'number') {
        result[key] = Number(Number(result[key]).toFixed(2))
      }
    })
  }
  let discount_mothed = []
  // set('会员优惠','促销-满额减现','促销-直接折扣','整单改价','积分抵扣','免单优惠')
  let discountArr = [{
    'key': 'free_discount_amount',
    'label': "免单优惠"
  }, {
    'key': 'cash_reduction_amount',
    'label': '抹零金额'
  }, {
    'key': 'discount_reduction_amount',
    'label': '整单改价'
  }, {
    'key': 'member_discount',
    'label': '会员优惠'
  }, {
    'key': 'discount_full_decrement',
    'label': '促销-满额减现'
  }, {
    'key': 'discount_direct',
    'label': '促销-直接折扣'
  }, {
    'key': 'integral_deduction',
    'label': '积分抵扣'
  }, {
    'key': 'goods_change_price',
    'label': '商品改价'
  }, {
    'key': 'coupon_discount',
    'label': '优惠券优惠'
  }]

  discountArr.forEach(item => {
    if (result[item.key]) {
      discount_mothed.push(item.label)
    }
  })

  result.discount_mothed = discount_mothed.toString()
  result.discountData = discountData
  const vipInfoIntegral = vipInfo && vipInfo.integral ? vipInfo.integral : 0
  let finalPrice = result.order_amount;
  if (result.integral_deduction) {
    finalPrice -= result.integral_deduction
  }
  if (result.cash_reduction_amount) {
    finalPrice -= result.cash_reduction_amount
  }
  result._max_can_use_integral = calcMaxIntegral(vipInfoIntegral, finalPrice, $vipSetting
    .max_integral_deduction, $vipSetting.satisfy_deduction_integral) //最多可使用积分

  result.order_discounts = []
  if (result.coupon_no) {
    result.order_discounts.push({
      act_no: result.coupon_no,
      act_name: couponInfo.coupon_title,
      act_type: '优惠券'
    })
  }
  if (discountData && discountData.promotionInfo) {
    result.order_discounts.push({
      act_no: discountData.promotionInfo.promotion_no,
      act_name: discountData.promotionInfo.promotion_name,
      act_type: '促销活动'
    })
  }


  result._orderData = {
    order_total_amount: result.order_total_amount, //订单总金额
    order_amount: result.order_amount, //应付金额
    discount_amount: result.discount_amount, //优惠金额
    member_no: member_no, //会员编号
    order_channel: otherData.order_channel || otherData.channel_source, //订单来源
    channel_source: otherData.order_channel || otherData.channel_source,
    remark: otherData.remark, //备注
    sales_clerk: otherData.sales_clerk, //收银员
    sales_clerk_staff: otherData.sales_clerk_staff, //营业员

    member_discount: result.member_discount, //会员优惠
    discount_full_decrement: result.discount_full_decrement, //促销-满额减现
    discount_direct: result.discount_direct, //促销-直接折扣
    change_price: result.change_price, //整单改价
    goods_change_price: result.order_detail.reduce((pre, cur) => {
      if (cur._is_change_price == true) {
        pre += cur.subtotal_amount
      }
      return pre
    }, 0), //商品改价
    integral_deduction: result.integral_deduction, //积分抵扣
    coupon_discount: result.coupon_discount, //优惠券优惠金额
    free_discount_amount: result.free_discount_amount, //免单优惠金额
    cash_reduction_amount: result.cash_reduction_amount, //抹零金额
    coupon_no: result.coupon_no, //优惠券编号
    use_integral: result.use_integral, //使用积分数量

    discount_mode: result.discount_mode, //打折、优惠方式
    discount_reduction_amount: result.discount_reduction_amount, //折扣减免金额
    discount_reason: otherData.discount_reason, //打折原因编号
    discount_reason_name: otherData.discount_reason_name, //打折、免单原因
    discount_mothed: result.discount_mothed, //优惠类型
    discount_type: result.discount_type,
    store_no: otherData && otherData.store_no ? otherData.store_no : '',
    "order_detail": result.order_detail.map(item => {
      return {
        "goods_no": item.goods_no,
        "goods_type": item.goods_type,
        "goods_barcode": item.goods_barcode,
        "goods_num": item.goods_num || item.amount,
        "sale_price": item.sale_price,
        "subtotal_amount": item.subtotal_amount,
        "discount_amount": item.discount_amount || 0, //优惠金额
        "ctual_amount": item.ctual_amount || 0, //实收金额
      }
    }),
    order_discounts: result.order_discounts
  }

  if (result._vip_pay_order_amount) {
    result._orderData.order_pays = [{
        "pay_type": "现金",
        "member_no": member_no,
        "amount": result && result._vip_pay_order_amount ? result._vip_pay_order_amount : 0,
        "remark": result.remark,
        "channel_source": otherData.channel_source, //订单来源
      },
      {
        "pay_type": '会员余额',
        "member_no": member_no,
        "amount": result && result._vip_pay_amount ? result._vip_pay_amount : 0,
        "remark": result.remark,
        "channel_source": otherData.channel_source, //订单来源
      }
    ]
  } else {
    result._orderData.order_pay = {
      "member_no": member_no,
      "pay_type": otherData && otherData.pay_type ? otherData.pay_type : '现金',
      "amount": result.order_amount,
      "remark": result.remark,
      "channel_source": otherData.channel_source, //订单来源
    }
  }


  // 通知安卓
  if (window && window.orderNative && window.orderNative.orderRes) {
    window.orderNative.orderRes(JSON.stringify(result))
  }

  return result
}


/**
 * 计算最大可用积分数量:
 * @property {number} integral 当前选择的会员可用积分数量
 * @property {number} order_amount 订单应付金额
 * @property {number} max_integral_deduction 一单最多可用积分抵扣百分之多少
 * @property {number} satisfy_deduction_integral satisfy_deduction_integral积分抵扣一块钱
 * @return {number} 本单最大可用积分抵扣的金额
 */
const calcMaxIntegral = (integral = 0, order_amount = 0, max_integral_deduction = 0, satisfy_deduction_integral =
  0) => {
  let num = integral;
  if (!num) {
    return 0
  }
  // 本单最大可用积分抵扣的金额
  let max = Number(max_integral_deduction * order_amount * 0.01)
  let amount = parseInt(num / satisfy_deduction_integral)
  if (amount > 0) {
    if (amount > max) {
      amount = parseInt(max)
    }
  }
  const res = amount * satisfy_deduction_integral || 0
  if (res && !isNaN(Number(res))) {
    return res
  }
  // 通知安卓
  if (window && window.orderNative && window.orderNative.orderRes) {
    window.orderNative.orderRes(res)
  }

  return 0
}

/**
 * @description 计算最接近当前输入积分的可用积分（satisfy_deduction_integral的最大整数倍）
 * @property {number} satisfy_deduction_integral satisfy_deduction_integral积分抵扣一块钱
 * @property {number} cur_input_integral 当前输入的积分数量
 * @property {number} max_can_use_integral 当前订单最大可用积分数量 ,就是calcBillResult方法得到的_max_can_use_integral
 * @return {number} 最接近当前输入积分的可用积分
 */
const calcNeedInputIntegral = (satisfy_deduction_integral = 0, cur_input_integral = 0, max_can_use_integral = 0) => {
  let needInputIntegral = 0
  let num = parseInt(cur_input_integral / satisfy_deduction_integral)
  if (num > 0) {
    let integral = num * satisfy_deduction_integral
    needInputIntegral = integral
  } else {
    needInputIntegral = 0
  }
  if (max_can_use_integral && needInputIntegral > max_can_use_integral) {
    needInputIntegral = max_can_use_integral
  }

  // 通知安卓
  if (window && window.orderNative && window.orderNative.pointRes) {
    window.orderNative.pointRes(needInputIntegral)
  }

  return needInputIntegral
}

/**
 * 计算可用促销活动以及使用该活动优惠的金额
 * @@property {Array} cartList - 购物车数据
 * @@property {Array} allPromotion - 所有促销活动
 * @@property {Object} memberLevelNo - 会员等级编号
 * 
 */
const calcUsablePromotions = (cartList, allPromotion, memberLevelNo) => {
  const cartGoodsNos = [...new Set(cartList.map(item => item.goods_no))]

  allPromotion = allPromotion.reduce((pre, cur) => {
    if (cartGoodsNos && cartGoodsNos.includes(cur.goods_no)) {
      if (cur && cur.participants === '指定会员等级') {
        if (!memberLevelNo || cur.member_level_name && memberLevelNo && cur.member_level_name.indexOf(
            memberLevelNo) === -1) {
          return pre
        }
      }

      if (cur && cur.weekly_take_effect) {
        let weekly = new Date().getDay() // 0-6
        let weekMap = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
        if (cur.weekly_take_effect.indexOf(weekMap[weekly]) === -1) {
          return pre
        }
      }
      const goods = cartList.find(e => e.goods_no === cur.goods_no)
      const activityIndex = pre.findIndex(item => item.promotion_no === cur.promotion_no)
      // 改价商品不能参加促销活动
      if (goods && activityIndex !== -1 && goods._is_change_price !== true) {
        pre[activityIndex]._goods_nos.push(cur.goods_no)
        pre[activityIndex]._goodsList.push({
          ...goods
        })
      } else if (goods && goods._is_change_price !== true) {
        cur._goods_nos = [cur.goods_no]
        cur._goodsList = [{
          ...goods
        }]
        pre.push(cur)
      }
    }
    return pre
  }, [])

  let result = []
  if (Array.isArray(allPromotion) && allPromotion.length > 0) {
    allPromotion.forEach(item => {
      const totalPrice = item._goodsList.reduce((pre, cur) => {
        pre += cur.sale_price * cur.amount
        return pre
      }, 0)
      if (item && item.promotion_mode === '满额减现' && Array.isArray(item._goodsList) && item._goodsList.length >
        0) {
        if (item.buy_full && totalPrice >= item.buy_full && item.discount_amount) {
          let rate = parseInt(totalPrice / item.buy_full)
          if (rate > 0) {
            if (item.whether_multiplication === '否') {
              // 不倍增
              rate = 1
            }
            const discountAmount = item.discount_amount || 0
            item._discount_full_decrement = -toFixed2(discountAmount * rate)
            item._discount_total_amount = item._discount_full_decrement
            item._rate = rate
            item._goodsList = item._goodsList.map(e => {
              e._buy_full_discount = toFixed2((e.sale_price * e.amount / totalPrice) * item
                ._discount_full_decrement)
              return e
            })
            result.push(item)
          }
        }
      } else if (item.promotion_mode === '直接折扣') {
        let discount = item.direct_discount || item.discount || 100
        let discount_direct = 0 //直接折扣减免的金额
        item._goodsList = item._goodsList.map(e => {
          e._discount_direct = -toFixed2(e.sale_price * e.amount * (100 - discount) / 100) //直接折扣减免的金额
          e._cur_sale_price = (e.sale_price * e.amount + e._discount_direct) / e.amount
          if (e.minimum_price && e._cur_sale_price < e.minimum_price && e.allow_min_sales_price === '不允许') {
            // 当前售价小于最低售价
            e._discount_direct = (e.minimum_price - e.sale_price) * e.amount
            e._cur_sale_price = e.minimum_price
          }
          discount_direct += e._discount_direct || 0
          return e
        })
        item._discount_direct = discount_direct
        item._discount_total_amount = discount_direct
        result.push(item)
      }
    })
  }
  return result.sort((a, b) => a._discount_total_amount - b._discount_total_amount)
}

export {
  calcNeedInputIntegral,
  calcMaxIntegral,
  calcBillResult
}

export default calcBillResult
